# Created with pycharm
# author:ju bai
# Date:2021/7/20
# Time:19:57
from selenium import webdriver
import unittest
import time
import os
from selenium.common.exceptions import NoAlertPresentException
from selenium.common.exceptions import NoSuchElementException


# 继承
class Baidu1(unittest.TestCase):
    # 测试固件

    # 每个测试方法之前运行
    def setUp(self):
        # 全局变量 self.
        print("--------setUp-------")
        self.driver = webdriver.Chrome()
        self.url = "https://www.baidu.com/"
        self.driver.maximize_window()
        time.sleep(3)

    # 每个测试方法之后运行
    def tearDown(self):
        print("--------tearDown-------")
        self.driver.quit()

    # 测试方法（用例）
    # 忽略测试用例执行
    @unittest.skip("skipping")
    def test_hao(self):
        driver = self.driver
        url = self.url
        driver.get(url)
        driver.find_element_by_link_text("hao123").click()
        time.sleep(6)

    # 测试方法要以test_开头
    def test_baidu(self):
        driver = self.driver
        url = self.url
        driver.get(url)
        driver.find_element_by_id("kw").send_keys("姜云升")
        driver.find_element_by_id("su").click()
        time.sleep(5)
        print(driver.title)
        # 断言
        # self.assertEqual(driver.title, "百度一下_百度搜索", msg="不相等")
        # # self.assertNotEqual(driver.title, "百度一下_百度搜索", msg="不相等")
        # self.assertTrue("cat" == "dog", msg="不相等")

        # 异常捕捉 错误截图
        try:
            self.assertEqual(u"ddd百度一下_你就知道", driver.title)
        except:
            # 出现异常就调用截图函数截图
            self.saveScreenAsPhoto(driver, "hao.png")
        time.sleep(6)

    # 错误截图函数(参数：驱动，截图名字)
    # 没调用不会执行
    def saveScreenAsPhoto(self, driver, file_name):
        if not os.path.exists("./image"):
            os.makedirs("./image")
        now = time.strftime("%Y%m%d-%H%M%S", time.localtime(time.time()))
        # 获取当前画面的截图
        driver.get_screenshot_as_file("./image/" + now + "-" + file_name)
        time.sleep(3)

    if __name__ == "__main__":
        unittest.main(verbosity=0)
